// -------------------------------------------------------------------------------------------------------------------
//
//  File: MainWindow.cpp
//
//  Copyright 2016 (c) Decawave Ltd, Dublin, Ireland.
//
//  All rights reserved.
//
//  Author:
//
// -------------------------------------------------------------------------------------------------------------------

#include "mainwindow.h"




#include "RTLSDisplayApplication.h"

#include "pointcloudwidget.h"

#include <QShortcut>
#include <QSettings>
#include <QDebug>
#include <QMessageBox>
#include <QDomDocument>
#include <QFile>
#include <QLine>
#include <QDateTime>
#include <QTimer>
#include "custommessagebox.h"

#include <ros/ros.h>


extern bool serial_connected;

bool language  = true;
bool startCalibration = false;  //[false: 未开始自标定] [true: 正在自标定]
QString BTN_sendSocketText= "停止";
QString LE_ip_addressText= "127.0.0.1";
QString ip_addressText= "127.0.0.1";
int LE_comTexttoInt= 6020;
MainWindow::MainWindow(QWidget *parent) :
    QWidget(parent)
{
    startRosCore();

    char *argv[] = {"leili_pathplaner"};
    std::string nodeName = "leili_pathplaner";
    int argc = 1;
    ros::init(argc, argv, nodeName,
              ros::init_options::AnonymousName);

    checkRosCore();

    m_rosThread = new RosThread(this);
    m_rosThread->start();

    initUI();
    createConnect();


    statusBarMessage(QtInfoMsg,"欢迎使用");
}

void MainWindow::onReady()
{
    QObject::connect(_SLAMWidget, SIGNAL(statusBarMessage), this, SLOT(statusBarMessage));
}

MainWindow::~MainWindow()
{
    if (m_rosThread->isRunning()) {
        m_rosThread->shutdown();
    }
}

SLAMwidget *MainWindow::pathWidget()
{
    return _SLAMWidget;
}

void MainWindow::onAboutAction()
{
    CustomMessageBox::information(nullptr,tr("About"),
                                  tr("<b>雷力自动规划上位机</b>"
                                                      "<br>version 2.0 (" __DATE__
                                                      ") <br>雷力工具.\n"
                                                                 "<br>http://www.leilitools.cn"));


}

void MainWindow::createConnect()
{
    RTLSDisplayApplication::connectReady(this, "onReady()");
    RTLSDisplayApplication::connectReady(_SLAMWidget, "onInitRviz()");


    QObject::connect(this->action_tcp_485,SIGNAL(triggered(bool)),this,SLOT(ShowTcp485Addr()));

    QObject::connect(this->action_cn,SIGNAL(triggered(bool)),this,SLOT(SetLanguage_cn()));
    QObject::connect(this->action_en,SIGNAL(triggered(bool)),this,SLOT(SetLanguage_en()));

    connect(m_listWidget,SIGNAL(currentRowChanged(int)),stackWidget,SLOT(setCurrentIndex(int)));
    connect(titleWidget,SIGNAL(ClickedMenuBtn()),this,SLOT(onShowMenu()));
    connect(m_btnSetting, &QPushButton::clicked,this,&MainWindow::onBtnSettingClick);
}


void MainWindow::statusBarMessage(QString status)
{
    tips->setText(status);
}

void MainWindow::statusBarMessage(QtMsgType type, QString msg)
{
    switch (type) {
     case QtDebugMsg:
        tips->setObjectName("tipsInfo");
        break;
    case QtWarningMsg:
        tips->setObjectName("tipsWarn");
        break;
    case QtCriticalMsg:
    case QtFatalMsg:
        tips->setObjectName("tipsError");
        break;
     case QtInfoMsg://当作成功吧
        tips->setObjectName("tipsSucc");
        break;
    }

    tips->setStyle(tips->style());
    tips->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ") + msg);
}

void MainWindow::onBtnSettingClick()
{
    m_preListIndex = stackWidget->currentIndex();
    m_listWidget->clearSelection();
    stackWidget->setCurrentWidget(m_settingW);
}

void MainWindow::initUI()
{
    setWindowTitle("雷力-路径规划");
    setWindowIcon(QIcon(":/icons/leili.ico"));

    setWindowFlags(Qt::FramelessWindowHint);


    setAttribute(Qt::WA_TranslucentBackground);
    this->setContentsMargins(0,0,0,0);



    titleWidget=new TitleBar(this);
    titleWidget->setObjectName("titleBarMax");

    InitLeft();
    InitRight();
    setMenu();


    setStackWidget();



    m_listWidget->setCurrentRow(0);

}

void MainWindow::InitRight()
{
    stackWidget = new QStackedWidget(this);
    stackWidget->setObjectName("right");
    stackWidget->setContentsMargins(0,0,0,0);


    tips = new QLabel(this);
    tips->setObjectName("tips");
    tips->setAlignment(Qt::AlignCenter);


    QVBoxLayout *main_layout=new QVBoxLayout(this);
    main_layout->setSpacing(0);
    main_layout->setContentsMargins(0, 0, 0, 0);
    main_layout->addWidget(titleWidget,0,Qt::AlignTop);

    m_leftWidget = new QWidget(this);
    m_leftWidget->setObjectName("left");
    m_leftWidget->setAttribute(Qt::WA_TranslucentBackground, false);
    m_leftWidget->setFixedWidth(150);

    QVBoxLayout *vleft = new QVBoxLayout(m_leftWidget);

    m_btnSetting = new QPushButton(m_leftWidget);
    m_btnSetting->setCursor(Qt::PointingHandCursor);
    m_btnSetting->setObjectName("btnSetting");
    m_btnSetting->setText("设置");

    vleft->addWidget(m_listWidget);
    vleft->addStretch();
    vleft->addWidget(m_btnSetting);

    QHBoxLayout *hLay=new QHBoxLayout(this);
    hLay->addWidget(m_leftWidget);

    m_right = new QWidget(this);
    m_right->setWindowOpacity(1.0);

    m_right->setObjectName("right");
    m_right->setStyle(m_right->style());
    //m_right->setContentsMargins(0, 0, 0, 0);


    QVBoxLayout *rVL = new QVBoxLayout(m_right);
    rVL->setContentsMargins(0,0,0,0);

    //rVL->addSpacing(8);
    rVL->addWidget(tips);
    //rVL->addSpacing(8);
    rVL->addWidget(stackWidget);
    //rVL->addSpacing(10);

    hLay->addWidget(m_right);
    main_layout->addLayout(hLay);
    //setWindowOpacity(0.96);

}

void MainWindow::InitLeft()
{
    m_listWidget = new QListWidget(this);
    m_listWidget->setSpacing(2);

    //m_listWidget->setCursor(Qt::PointingHandCursor);

    m_listWidget->setObjectName("mainleft");
    m_listWidget->setStyle(m_listWidget->style());

    int itemHight=32;
    QListWidgetItem *lader = new QListWidgetItem(m_listWidget);
    lader->setSizeHint(QSize(lader->sizeHint().width(), itemHight));


    lader->setIcon(QIcon(":/list/list/slam_hover.svg"));
    lader->setText("数据采集");


    QListWidgetItem *SLAM = new QListWidgetItem(m_listWidget);
    SLAM->setSizeHint(QSize(SLAM->sizeHint().width(), itemHight));
    SLAM->setIcon(QIcon(":/list/list/slam_hover.svg"));
    SLAM->setText("SLAM建图");

    QListWidgetItem *pointCloud = new QListWidgetItem(m_listWidget);
    pointCloud->setSizeHint(QSize(pointCloud->sizeHint().width(), itemHight));
    pointCloud->setIcon(QIcon(":/list/list/slam_hover.svg"));
    pointCloud->setText("三维点云");


    QListWidgetItem *gridMap = new QListWidgetItem(m_listWidget);
    gridMap->setSizeHint(QSize(gridMap->sizeHint().width(), itemHight));
    gridMap->setIcon(QIcon(":/list/list/slam_hover.svg"));
    gridMap->setText("栅格地图");


    QListWidgetItem *pathPlan = new QListWidgetItem(m_listWidget);
    pathPlan->setSizeHint(QSize(pathPlan->sizeHint().width(), itemHight));
    pathPlan->setIcon(QIcon(":/list/list/slam_hover.svg"));
    pathPlan->setText("路径规划");

    QListWidgetItem *uwb = new QListWidgetItem(m_listWidget);
    uwb->setSizeHint(QSize(uwb->sizeHint().width(), itemHight));
    uwb->setIcon(QIcon(":/list/list/slam_hover.svg"));
    uwb->setText("uwb定位");

    QListWidgetItem *pathFollow = new QListWidgetItem(m_listWidget);
    pathFollow->setSizeHint(QSize(pathFollow->sizeHint().width(), itemHight));
    pathFollow->setIcon(QIcon(":/list/list/slam_hover.svg"));
    pathFollow->setText("路径跟踪");


    QListWidgetItem *moveControl = new QListWidgetItem(m_listWidget);
    moveControl->setSizeHint(QSize(moveControl->sizeHint().width(), itemHight));
    moveControl->setIcon(QIcon(":/list/list/slam_hover.svg"));
    moveControl->setText("运动控制");


    QListWidgetItem *plan = new QListWidgetItem(m_listWidget);
    plan->setSizeHint(QSize(plan->sizeHint().width(), itemHight));
    plan->setIcon(QIcon(":/list/list/path_hover.svg"));
    plan->setText("路径规划");


    QListWidgetItem *control = new QListWidgetItem(m_listWidget);
    control->setSizeHint(QSize(control->sizeHint().width(), itemHight));
    control->setIcon(QIcon(":/list/list/control_hover.svg"));
    control->setText("遥控面板");


    QListWidgetItem *viewSetting = new QListWidgetItem(m_listWidget);
    viewSetting->setSizeHint(QSize(viewSetting->sizeHint().width(), itemHight));
    viewSetting->setIcon(QIcon(":/list/list/setting_hover.svg"));
    viewSetting->setText("视图设置");

    m_listWidget->adjustSize();


    int itemCount = m_listWidget->count();
    // 获取单个项目的高度（包括边框和间距）
    int itemHeight = m_listWidget->sizeHintForRow(0) +
            m_listWidget->spacing() * 2; // 估算间距

    // 设置固定高度（限制最大高度，避免过长）
    int newHeight = itemCount * itemHeight +
            2 * m_listWidget->frameWidth(); // 考虑边框

    m_listWidget->setFixedHeight(newHeight);
}

void MainWindow::setMenu()
{
    menu = new QMenu(this);

    action_cn = new QAction(this);
    action_cn->setText("中文");

    action_en = new QAction(this);
    action_en->setText("英文");

    action_tcp_485 = new QAction(this);

    actionAbout = new QAction(this);
    actionAbout->setText("关于雷力工具");
    menu->addAction(action_cn);
    menu->addAction(action_en);
    menu->addAction(actionAbout);
}

void MainWindow::setStackWidget()
{
    _SLAMWidget = new SLAMwidget(m_right);

    _speedMonitorDlg = new SpeedMonitorWidget(m_right);

    m_ladarWidget = new LadarWidget(m_right);
    m_pointcloudwidget = new PointCloudWidget(m_right);
    m_gridMapW = new GridMapWidget(m_right);
    m_pathPlanW = new PathPlanWidget(m_right);
    m_uwbW = new UWBWidget(m_right);
    m_pathFollowW = new PathFollowWidget(m_right);
    m_moveControlW = new MoveControlWidget(m_right);
    m_settingW = new SettingWidget(m_right);


    stackWidget->addWidget(m_ladarWidget);
    stackWidget->addWidget(_SLAMWidget);
    stackWidget->addWidget(m_pointcloudwidget);
    stackWidget->addWidget(m_gridMapW);
    stackWidget->addWidget(m_pathPlanW);
    stackWidget->addWidget(m_uwbW);
    stackWidget->addWidget(m_pathFollowW);
    stackWidget->addWidget(m_moveControlW);
    stackWidget->addWidget(_speedMonitorDlg);
    stackWidget->addWidget(m_settingW);


}

void MainWindow::startRosCore()
{
    QProcess *process = new QProcess(this);
    process->setProgram(QString("/opt/ros/melodic/bin/roscore"));
    process->startDetached();

    if (!process->waitForStarted())
    {
        qWarning() << "roscore start failed." << process->errorString();
        process->deleteLater();
    }else{
        qDebug() << "roscore start succ";
    }
}

//根据官方文档，应该在ros::init之后的任意时间调用
void MainWindow::checkRosCore()
{
    QTimer::singleShot(1000,nullptr,[](){
        //QMessageBox::critical(NULL,"","roscore未能启动，请先保证已启动roscore");
        qDebug() << "wait roscore timeout....";
        //exit(0);
    });

    while (!ros::master::check()) {
            qDebug() << "wait roscore start....";
            QThread::msleep(200);
    }
}

void MainWindow::SetLanguage_cn()
{       
    translator.load(":/new/prefix1/lanague_cn.qm");
    qApp->installTranslator(&translator);
    language=true;

}
void MainWindow::SetLanguage_en()
{  
    translator.load(":/new/prefix1/lanague_en.qm");
    qApp->installTranslator(&translator);
    language=false;

}

void MainWindow::ShowTcp485Addr()
{
    _speedMonitorDlg->show();
}

void MainWindow::onShowMenu()
{
     menu->exec(cursor().pos());
}

bool MainWindow::event(QEvent *event)
{
    if(event->type() == QEvent::LanguageChange)
    {


    }else if(event->type() == QEvent::Resize)
    {
        if(isMaximized())
        {
            m_leftWidget->setObjectName("left");
            stackWidget->setObjectName("right");
            m_right->setObjectName("right");
        }
        else
        {
            stackWidget->setObjectName("rightRadius");
            m_leftWidget->setObjectName("mainleftRadius");
            m_right->setObjectName("rightRadius");
        }

        stackWidget->setStyle(stackWidget->style());
        m_leftWidget->setStyle(m_listWidget->style());
        m_right->setStyle(m_right->style());
    }

    return QWidget::event(event);
}





